#include"../source/serve.hpp"
// void Close(Channel* channel)
// {
//    DBG_LOG("close:%d",channel->Fd());
//     channel->Remove();
//     delete channel;
// }
// void HandleRead(Channel* channel)
// {
//     int fd=channel->Fd();
//     char buf[1024]={0};
//     int ret=recv(fd,buf,1023,0);
//     if(ret<0){
//          if (errno != EAGAIN && errno != EINTR) {
//         // 打印具体错误信息
//         printf("recv failed! errno=%d, reason: %s\n", errno, strerror(errno));}
//         return Close(channel);}

//     DBG_LOG("%s",buf);
//     channel->EableWrite();
// }
// void HandleWrite(Channel* channel)
// {
//     int fd=channel->Fd();
//     const char* buf="今天是雨天";
//     int ret=send(fd,buf,strlen(buf),0);
//     if(ret<0) return Close(channel);
//     channel->DisableWrite();
// }
// void HandleError(Channel* channel)
// {
//     Close(channel);
// }
// void Event(EventLoop* loop,Channel* channel,uint64_t timerid)
// {
//     loop->TimerRefresh(timerid);
// }

EventLoop loop;
//管理所有连接对象
std::unordered_map<uint64_t,PtrConnection> conns;
 uint64_t conid=0;

 std::vector<LoopThread> threads(2);
 int next_loop=0;
  LoopThreadPool *loop_pool;
void ConnectionDestory(const PtrConnection& conn)
{
    
    DBG_LOG("从连接池中移除连接---------------------");
    conns.erase(conn->Id());
}

void OnConnected(const PtrConnection& conn)
{
    DBG_LOG("NEW CONNECTION:%p",conn.get());
}
void OnMessage(const PtrConnection& conn ,Buffer* buf)
{
    DBG_LOG("%s",buf->ReaderPosition());
    DBG_LOG("buf readable:%ld",buf->ReadAbleSize());
    buf->MoveReadOffset(buf->ReadAbleSize());
    std::string str="hello world";
    conn->Send(str.c_str(),str.size());
    conn->ShutDown();
}
void NewConnection(int fd)
{
    conid++; 

    PtrConnection conn(new Connection(loop_pool->NextLoop(),conid,fd));
   
    conn->SetMessageCallback(std::bind(OnMessage,std::placeholders::_1,std::placeholders::_2));
    conn->SetConnectedCallback(std::bind(OnConnected,std::placeholders::_1));
    conn->SetSrvClosedCallback(std::bind(ConnectionDestory,std::placeholders::_1));
   

    conn->EnableInactiveRelease(10);//启动非活跃销毁
    conn->Establish();//
    conns.insert(std::make_pair(conid, conn));
  
    DBG_LOG("我是主线程");
}
int main()
{
    loop_pool=new LoopThreadPool(&loop);
    loop_pool->SetThreadCount(2);
    loop_pool->Create();
    
    Acceptor acceptor(&loop,8080);
    acceptor.SetAcceptorCallback(std::bind(NewConnection,std::placeholders::_1));
    acceptor.Listen();
     loop.Start();
    return 0;
}